﻿using AppDataStruct;
using ComLib.ComType;
using CVR100AReader;
using DeviceCommon;
using KWindow.KPageCore;
using LogLib;
using Newtonsoft.Json;
using SoftKeyBoard;
using System;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageReadIDCardInfo : PageControlBase
    {            
        //private DeviceControl _device = null;

        private IDCardAll _cardInfo = null;

        private PictureBox pictureBox1 = null;

        private Label labelInputTip = null;

        private Button buttonInputID = null;

        //private CVRReader _reader = null;

        //private IDCardAll _cardInfo = null;

        public PageReadIDCardInfo()
        {
            //InitCardReader();
            InitializeComponent();
            SetProcessBase(ProcessReadIDCardInfo.Instance);            
        }


        protected override void btnNext_Click(object sender, EventArgs e)
        {
            _cardInfo = new IDCardAll();
            _cardInfo.address = "广东省";
            _cardInfo.birthday = "1999-03-05";
            _cardInfo.validtermOfStart = "2021-12-31";
            _cardInfo.HeadImage = null;
            _cardInfo.IsManualInputNumberVerify = false;
            _cardInfo.signdate = "泰山派出所";
            _cardInfo.name = "绿三";
            _cardInfo.people = "汉族";
            _cardInfo.sex = "男";
            _cardInfo.number = "4322341199903052312";
            base.StopWork();
            base.btnNext_Click(sender,e);
        }

        private void GetControls()
        {
        
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
            labelInputTip = GetControl<Label>("labelInputTip") as Label;
            buttonInputID = GetControl<Button>("buttonInputID") as Button;
            SetButtonDefaultStyles(buttonInputID);          
        }
       

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            //_device = new DeviceControl(DeviceList.CVR100A);
            //_device.OnCatchException = OnCatchException;
            //_device.OnWorkingDone = OnReadSuccess;
            //_device.OnWorkingFailed = OnReadFailed;
            //_device.OnTimeout = OnReadTimeout;
            //_device.Init();
            ////SetTip(DicPrompts["Tips"].Text);
            SetTip("请把本人身份证放置于身份证阅读区");
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {

            if (null != _cardInfo && _cardInfo.IsManualInputNumberVerify)
            {
                SFZInfo info = new SFZInfo();
                info.Address = _cardInfo.address.Trim();
                info.BirthDate = _cardInfo.birthday;
                info.ExpiryDate = _cardInfo.validtermOfStart + "-" + _cardInfo.validtermOfEnd;
                info.HeaderPicturePath = _cardInfo.HeadImage;
                info.IsManualInputNumberVerify = _cardInfo.IsManualInputNumberVerify;
                info.IssueUnit = _cardInfo.signdate;
                info.Name = _cardInfo.name.Trim();
                info.Nation = _cardInfo.people;
                info.Sex = _cardInfo.sex;
                info.SFZH = _cardInfo.number;
                Process.SetValue("SFZInfo", info);
            }

            base.UpdateData();
            //string personDir = _config.OutputDirs[_cardInfo.number];
            //Process.SetValue("PersonDataDirectory", personDir);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            //if (_device != null)
            //{
            //    _device.Dispose();
            //    _device = null;
            //}
            _cardInfo = null;
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
            //if(_reader == null)
            //{
            //    return;
            //}
            //if (_reader.Inited && !_reader.Exited)
            //{
            //    _reader.Close();
            //}
            //_reader.DeleteTempData();
        }
    
        //public override void StartWork()
        //{
        //    base.StartWork();
        //    //string temp = "";
        //    //_reader.Start("", out temp);
        //    //Speak("");
        //    //if(_device != null)
        //    //{
        //    //    _device.Start();
        //    //}            
        //}

        //public override void StopWork()
        //{
            //base.StopWork();
            //string temp = "";
            //_reader.Stop("", out temp);
            //if(_device != null)
            //{
            //    _device.Stop();
            //}
        //}

        //private void OnReadSuccess(string outParams)
        //{
        //    string msg = string.Format("读取结果: \n{0}", outParams);
        //    Log.WriteAsync(msg);
        //    Speak("身份证读取成功，请保管好您的身份证");
        //    // 在这里处理身份证信息解析结果
        //    _cardInfo = JsonConvert.DeserializeObject<IDCardAll>(outParams);
        //    Action<string> handler = (e) =>
        //    {
        //        UpdateData();
        //        ClearData();
        //        Process.ToNext();
        //    };
        //    this.Invoke(handler, msg);
        //}

        //private void OnReadFailed(string outParams, string error)
        //{
        //    string msg = string.Format("身份证信息读取错误: \n{0}", error);
        //    Log.WriteAsync(msg);
        //    Action<string> handler = (e) =>
        //    {
        //        MessageBox.Show(e);
        //        ClearData();
        //        Process.ToHome();
        //    };
        //    this.Invoke(handler, msg);
        //}

        //private void OnReadTimeout(string outParams)
        //{
        //    string msg = string.Format("读取身份证信息超时: \n{0}", outParams);
        //    Log.WriteAsync(msg);
        //    Action<string> handler = (e) =>
        //    {
        //        MessageBox.Show(e);
        //        StopWork();
        //        ClearData();
        //        Process.ToHome();
        //    };
        //    this.Invoke(handler, msg);
        //}

        //private void OnCatchException(string outParams)
        //{
        //    string msg = string.Format("设备运行发生了异常: \n{0}", outParams);
        //    Log.WriteAsync(msg);
        //    Action<string> handler = (e) =>
        //    {
        //        MessageBox.Show(e);
        //        StopWork();
        //        ClearData();
        //        Process.ToHome();
        //    };
        //    this.Invoke(handler, msg);
        //}

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            Process.StopWork();
            if (Process.Job != null)
            {
                Process.Job.Cancel("倒计时结束，读取身份证操作未完成，取消预受理.");
            }
            base.OnCountdownCompleted(sender, e);
        }

        private void buttonInputID_Click(object sender, EventArgs e)
        {
            string inputIDNumber = "";
            string inputXM = "";
            //StopWork();
            Process.StopWork();
            if (StartManualInput(out inputIDNumber, out inputXM))
            {
                IDCardAll idcard = Process.GetValue<IDCardAll>("IDCardInfo");
                if(idcard != null && !string.IsNullOrEmpty(idcard.number))
                {
                    //身份证已经读取过了，不再处理
                    Log.WriteAsync($"已经读取身份证到身份证{idcard.number},忽略人工输入{inputIDNumber}");
                    return;
                }
                _cardInfo = new IDCardAll();
                _cardInfo.number = inputIDNumber;
                _cardInfo.name = inputXM;
                _cardInfo.birthday = IDCardCheck.GetBirthday(inputIDNumber);
                _cardInfo.sex = IDCardCheck.GetSex(inputIDNumber);
                _cardInfo.IsManualInputNumberVerify = true;
                UpdateData();
                //ClearData();
                Process.ToNext();
            }
            else
            {
                Process.StartWork();
            }
        }

        private bool StartManualInput(out string SFZH, out string XM)
        {
            SFZH = "";
            XM = "";
            bool bRet = false;
            Log.WriteAsync("用户启动了身份证人工输入操作...");
            FormInputID formInputID = new FormInputID();
            Speak("请输入您的身份证号码");
            if (formInputID.ShowDialog() == DialogResult.OK)
            {              
                SFZH = formInputID.Number;
                Log.WriteAsync($"用户人工输入的身份证号码是:{SFZH}");
                bRet = true;
            }
            else
            {
                Log.WriteAsync("用户取消了人工输入...");
                bRet = false;
            }          
            return bRet;
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            Process.StopWork();
           
            base.btnCancel_Click(sender, e);
        }        
    }
}
